package com.album.http;

import java.io.BufferedReader;   
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;   
import java.net.HttpURLConnection;   
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;   
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import com.album.R;
import com.album.activity.MessageDialog;
import com.album.task.ICallBack;
import com.album.utils.CommonUtil;
import com.album.utils.MyLog;

import android.R.integer;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

    
/**  
 * HTTP 
 *   
 * @author Rome 
 * 2011.6.27 
 */  
public class HttpRequest {   
    //----------test  vipshop public_api-------------------
	private static String  TAG = "HttpRequester";
    private String xmlStr="";
    public final static String error= "HttpRequest_Error";
    public static String sendDataPost(Context ctx,String strUrl, String outData,ICallBack resTask) {
    	Log.i(TAG, "sendDataPost()："+strUrl);
    	if (CommonUtil.CheckNetWork(ctx)) {
    		HttpURLConnection httpConn = null;
        	String xmlStr = null;
    		try {
    			if (CommonUtil.isWap()) {
    				Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
    						new InetSocketAddress("10.0.0.172", 80));
    				httpConn = (HttpURLConnection) new URL(strUrl)
    						.openConnection(proxy);
    			} else {
    				httpConn = (HttpURLConnection) new URL(strUrl).openConnection();
    			}
    			HttpURLConnection.setFollowRedirects(false);
    			httpConn.setDoInput(true);
    			httpConn.setDoOutput(true);
    			httpConn.setReadTimeout(15000);
    			httpConn.setConnectTimeout(15000);
    			httpConn.setRequestProperty("Accept-Charset", "utf-8");
    			httpConn.setRequestProperty("Content-Type", "html/xml");
    			httpConn.setRequestProperty("User-Agent", "systempatch");
    			httpConn.setInstanceFollowRedirects(false);
    			// send out data using POST method
    			httpConn.setRequestMethod("POST");
    			
    			httpConn.connect();
    			
    			DataOutputStream dout = new DataOutputStream(httpConn.getOutputStream());
    			if(outData != null)
    			dout.write(outData.getBytes());
    			dout.flush();
    			dout.close();
    			// receive the response
    			int rspCode = httpConn.getResponseCode();
    			System.out.print("rspCode :"+rspCode+"\r\n");
    			int i = 0;
    			// process HTTP 200-OK
    			if(rspCode == HttpsURLConnection.HTTP_OK) {
    				BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));

    				String strLine;
    				StringBuffer rspBuf = new StringBuffer(); 
    				while((strLine=br.readLine()) != null) {
    					 rspBuf.append(strLine + "\r\n");
    				}
    				xmlStr = rspBuf.toString();
    				br.close();
    				
    				httpConn.getInputStream().close();
    				httpConn.disconnect();
    				return xmlStr;
    				//错误处理
    			}else if(rspCode == HttpsURLConnection.HTTP_NOT_FOUND || rspCode == HttpsURLConnection.HTTP_BAD_REQUEST
    					|| rspCode == HttpsURLConnection.HTTP_INTERNAL_ERROR){
    				Log.i(TAG, "404,check the http or....");
    				resTask.HttpError(rspCode);
    			}else {
    				resTask.HttpError(rspCode);
    			}
    			return xmlStr;
    		}
    		catch(Exception e) {
    			xmlStr = null;
    			e.printStackTrace();
    			MyLog.info(HttpRequest.class, "time out:");
    			resTask.TimeOut();
    			return xmlStr;
    		}
		}else{
			//网络异常
			resTask.HttpError(0);
			return error;
		}
    	
	}
    /**
     * 上传图片、文件 post
     * @param path
     * @param params
     * @param file
     * @throws Exception
     */
	public static String uplaodPost(Context ctx, String path,
			Map<String, String> params, FormFile file,ICallBack resTask) throws Exception {
		if (CommonUtil.CheckNetWork(ctx)) {
			return uplaodPost(path, params, new FormFile[] { file },resTask);
		} else {
			return error;
		}
	}
    /**
     * 上传图片、文件 http请求
     * @param path
     * @param params
     * @param file
     * @throws Exception
     */
	public static String uplaodPost(String path, Map<String, String> params,
			FormFile[] files,ICallBack resTask) {
		String BOUNDARY = "---------------------------7da2137580612"; // 数据分隔线
		String MULTIPART_FORM_DATA = "multipart/form-data";
		final String endline = "--" + BOUNDARY + "--\r\n";// 数据结束标志
		String result = null;
			StringBuilder sb = new StringBuilder();
			int fileDataLength = 0;
			for (FormFile uploadFile : files) {// 得到文件类型数据的总长度
				StringBuilder fileExplain = new StringBuilder();
				fileExplain.append("--");
				fileExplain.append(BOUNDARY);
				fileExplain.append("\r\n");
				fileExplain.append("Content-Disposition: form-data;name=\""
						+ uploadFile.getParameterName() + "\";filename=\""
						+ uploadFile.getFilname() + "\"\r\n");
				fileExplain.append("Content-Type: "
						+ uploadFile.getContentType() + "\r\n\r\n");
				fileExplain.append("\r\n");
				fileDataLength += fileExplain.length();
				if (uploadFile.getInStream() != null) {
					fileDataLength += uploadFile.getFile().length();
				} else {
					fileDataLength += uploadFile.getData().length;
				}
			}
			// 上传的表单参数部分，格式请参考文章
			for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
				sb.append("--");
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getKey() + "\"\r\n\r\n");
				sb.append(entry.getValue());
				sb.append("\r\n");
			}
			byte[] entitydata = sb.toString().getBytes();// 得到实体数据
			// 计算传输给服务器的实体数据总长度
			int dataLength = sb.toString().getBytes().length + fileDataLength
					+ endline.getBytes().length;
			
			HttpURLConnection httpConn =null;
			try {
				if (CommonUtil.isWap()) {
					Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
							new InetSocketAddress("10.0.0.172", 80));
					httpConn = (HttpURLConnection) new URL(path)
							.openConnection(proxy);
				} else {
					httpConn = (HttpURLConnection) new URL(path).openConnection();
				}
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");
//			httpConn.setRequestProperty("Content-Length",
//					String.valueOf(dataLength));
			httpConn.setRequestProperty("Content-Type",
					MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
			DataOutputStream dos = new DataOutputStream(
					httpConn.getOutputStream());
			dos.write(entitydata);
			// 把所有文件类型的实体数据发送出来
			for (FormFile uploadFile : files) {
				StringBuilder fileEntity = new StringBuilder();
				fileEntity.append("--");
				fileEntity.append(BOUNDARY);
				fileEntity.append("\r\n");
				fileEntity.append("Content-Disposition: form-data;name=\""
						+ uploadFile.getParameterName() + "\";filename=\""
						+ uploadFile.getFilname() + "\"\r\n");
				fileEntity.append("Content-Type: "
						+ uploadFile.getContentType() + "\r\n\r\n");
				dos.write(fileEntity.toString().getBytes());
				if (uploadFile.getInStream() != null) {
					byte[] buffer = new byte[1024];
					int len = 0;
					int len2 = 0;
					while ((len = uploadFile.getInStream()
							.read(buffer, 0, 1024)) != -1) {
						dos.write(buffer, 0, len);
						len2 = len2 + len;
						System.out.println("dataLength,len:"
								+ uploadFile.getFile().length() + "," + len2);
					}
					uploadFile.getInStream().close();
				} else {
					dos.write(uploadFile.getData(), 0,
							uploadFile.getData().length);
				}
				dos.write("\r\n".getBytes());
			}
			byte[] end_data = endline.getBytes();// 数据结束标志
			dos.write(end_data);
			dos.flush();
			InputStream is = null;
			int resCode = httpConn.getResponseCode();
			if(resCode == 200){
		    is = httpConn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
		    result = br.readLine();
			System.out.println("resunlt:" + result);
			}else if(resCode == HttpsURLConnection.HTTP_NOT_FOUND){
				Log.i(TAG, "404,check the http or....");
				resTask.HttpError(resCode);
			}else if(resCode == HttpsURLConnection.HTTP_BAD_REQUEST){
				Log.i(TAG, "400,check the param or....");
				resTask.HttpError(resCode);
			}else if(resCode == HttpsURLConnection.HTTP_INTERNAL_ERROR){
				Log.i(TAG, "500,check the service or....");
				resTask.HttpError(resCode);
			}
			dos.close();
			is.close();
		
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}  
